﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Configuration;
using YQBlog.Models;
using Common;
using Ninject;
using System.Collections;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using YQBlog.General;
using res = Resource.Controllers.Home.Home;
using System.Web.UI;
using System.Web.Security;
using System.Runtime.Remoting.Messaging;
using System.Web.Profile;

namespace YQBlog.Controllers
{
    [WebFilter]
    public class HomeController : Controller
    {
        [Inject]
        public IServices myService { get; set; }
        GeneralConfigInfo configinfo = YQBlog.General.WebUtils.configinfo;

        /// <summary>
        /// 首页
        /// </summary>
       [OutputCache(CacheProfile = "CacheMain")]
        public ActionResult Index(int? p, int? commend, string theme = "")
        {
            if (theme!="")
                WebUtils.ChangeTheme(theme);
            int iscommend = commend ?? 0;
            ViewBag.now = DateTime.Now.ToString();
            ViewBag.Title = configinfo.Webtitle;
            List<CategoryModel> lst = myService.GetIndexCategoryList();
            
            foreach(CategoryModel category in lst)
            {
                if (category.Type == "1" && Utils.StrToInt(category.ListNum) > 0)
                {
                    ViewData["DL_" + category.CateId] = myService.GetArticles(0, Convert.ToInt32(category.CateId), Utils.StrToInt(category.ListNum));
                }
                else if (category.Type == "2")
                {
                    ViewData["Data_" + category.CateId] = new blog_varticle();
                    var re = myService.GetArticles(0, Utils.StrToInt(category.CateId), 0);
                    if (re.Count() > 0)
                    {
                        ViewData["Data_" + category.CateId] = re.ToList()[0];
                    }
                }
                else if (category.Type == "7")
                {
                    var re = myService.GetArticles(0, Utils.StrToInt(category.CateId), 0);
                    if (re.Count() > 0)
                    {
                        foreach (blog_varticle varticle in re)
                        {
                            ViewData["D_" + varticle.id.ToString()] = varticle;
                        }
                    }
                }
            }
            //文章按天归档
            string strArticleDates = "[";
            foreach (string a in myService.GetArticleDates())
            {
                strArticleDates += "\""+a+"\",";
            }
            strArticleDates = "var strArticleDates=" + strArticleDates.Trim(',') + "];";
            ViewBag.ArticleDates = strArticleDates;
            //文章归档
            ViewBag.ArticleArchives = myService.GetArticleArchives();
            //访问最多的文章10条
            ViewBag.MostViewArticles = myService.GetArticles(1, 0, 10,field:"viewcount");
            //推荐最多的文章10条
            ViewBag.MostCommendArticles = myService.GetArticles(1, 0, 10, field:"favor");
            //评论最多的文章10条
            ViewBag.MostReplyArticles = myService.GetArticles(1, 0, 10, field:"subcount");
            //有最新评论文章10条
            ViewBag.NewReplyArticles = myService.GetArticles(1, 0, 10, field:"lastreplydate");
            //最新文章评论10条
            ViewBag.NewArticleReplies = myService.GetReplyArticles(1, 0, 10);
            //tags
            ViewBag.Tags = myService.GetTagList(1, 0);
            ViewBag.ArticleCount = myService.GetArticleCountByType(1);
            ViewBag.AlbumCount = myService.GetArticleCountByType(4);
            ViewBag.NoteCount = myService.GetArticleCountByType(6);
            ViewBag.ArticleReplyCount = myService.GetArticleCountByType(1,1);
            ViewBag.AlbumReplyCount = myService.GetArticleCountByType(4,1);

            Pager pager = new Pager();
            pager.PageNo = p ?? 1;
            pager.PageSize = configinfo.IndexPagerCount;
            pager = myService.GetArticlePaging(pager, 1, 0, iscommend);
            ViewBag.PageNo = p ?? 1;
            ViewBag.PageCount = pager.PageCount;
            string jsonSummaryImg = "";
            pager.Entity = GetNewArticleQuery(pager.Entity as IQueryable<blog_varticle>, out jsonSummaryImg);
            ViewBag.SummaryImgs = jsonSummaryImg;
            return View(pager.Entity);
        }

        /// <summary>
        /// 记录结果处理
        /// </summary>
        private IQueryable<ArtilceWithDecorate> GetNewArticleQuery(IQueryable<blog_varticle> d, out string jsonSummaryImg)
        {
            configinfo.DecorateImgCount = WebUtils.GetDecorateCount(WebUtils.GetCurrentTheme());
            List<ArtilceWithDecorate> list = new List<ArtilceWithDecorate>();
            string str = "[";
            string img = "";
            int tmpKey = 0;
            Random ran = new Random();

            string themepath = WebUtils.GetCurrentTheme() == "" ? "/Content/" : "/Themes/" + WebUtils.GetCurrentTheme() + "/Content/";

            foreach (blog_varticle a in d)
            {
               //提取summary中第一张图
                img = Utils.GetImg(a.summary);
                //提取内容中的第一张图
                //if (img == "")
                //    img = Utils.GetImg(a.content);
                if (img == "" && configinfo.DecorateImgCount > 0)
                {
                    int RandKey = ran.Next(1001, 1000 + configinfo.DecorateImgCount);
                    if (RandKey == tmpKey)
                        RandKey++;
                    RandKey = RandKey > 1000 + configinfo.DecorateImgCount ? 1001 : RandKey;
                    tmpKey = RandKey;


                    img = themepath+"image/decorate/" + RandKey.ToString() + ".jpg";
                } 
                if (img != "")
                    str += "{\"id\":\"" + a.id.ToString() + "\",\"img\":\"" + img + "\"},";

                list.Add(
                    new ArtilceWithDecorate
                    { 
                        id=a.id,
                        title=a.title,
                        cateid=a.cateid,
                        typeid=a.typeid,
                        createdate=a.createdate,
                        viewcount=a.viewcount,
                        subcount=a.subcount,
                        catepath = myService.GetCategoryPathUrl(a.catepath),
                        rename=a.rename,
                        url=a.url,
                        istop=a.istop,
                        iscommend=a.iscommend,
                        Decorate=img,
                        summary = Utils.ClearImgs(a.summary).Trim() == "" ? Utils.CutString(Utils.RemoveHtml(a.content), 0, configinfo.MaxSummaryCharCount) + "..." : Utils.ClearImgs(a.summary),
                        FullSummary = a.summary.Trim() == "" ? Utils.CutString(Utils.RemoveHtml(a.content), 0, configinfo.MaxSummaryCharCount) + "..." : a.summary.Trim()
                    });
            }
            jsonSummaryImg = "var summaryimgs=" + str.Trim(',') + "];";
            return list.AsQueryable<ArtilceWithDecorate>();
        }

        /// <summary>
        /// 分类页,别名访问
        /// </summary>
        [OutputCache(CacheProfile = "CacheMain")]
        public ActionResult CategoryByKey(string key, int? p, int? commend, int? f)
        {
            int iscommend = commend ?? 0;
            CategoryModel category = myService.GetCategoryByReName(key);
            if (category != null)
            {
                return Category(Utils.StrToInt(category.CateId), p, iscommend, f ?? 0);
            }
            else
            {
                return View("Error");
            }
        }

        /// <summary>
        /// 分类页，ID访问
        /// </summary>
        [OutputCache(CacheProfile = "CacheMain")]
        public ActionResult Category(int id, int? p, int? commend, int? f)
        {
            try
            {
                CategoryModel category = myService.GetCategoryByID(id);
                ViewBag.Title = category.CateName;
                ViewBag.WebPath = myService.GetCategoryPathUrl(category.Path);
                string currenturl = WebUtils.GetCateUrl(category);
                ViewBag.CurrentUrl = currenturl;
                Pager pager = new Pager();
                pager.PageNo = p ?? 1;

                switch(category.Type)
                {
                    //单页
                    case "2":
                        blog_varticle varticle = new blog_varticle();
                        var re = myService.GetArticles(0,id,0);
                        if (re.Count() > 0)
                        {
                            varticle = re.ToList()[0];
                            varticle.viewcount++;
                            myService.UpdateArticle(varticle);
                            ViewBag.VoteTip = IsVote(varticle.id) ? res.Vote_Tip1 : res.Vote_Tip2;
                            ViewBag.PreNextLink = GetNextPreArticleLink(varticle.id);
                            ViewBag.ArticleId = varticle.id;
                            return View(WebUtils.GetViewName(category.CustomView, "Article"), varticle);
                        }
                        else
                            return View("Error");
                    //相册
                    case "4":
                        return View(WebUtils.GetViewName(category.CustomView, "Albums"), myService.GetAlbums(id));
                    //留言板
                    case "6":
                        if ((f ?? 0) > 0)
                        {
                            int floorpage = myService.GetArticlePageNo(configinfo.NotePagerCount, id, f ?? 0, 2);
                            string paras = "";
                            paras += floorpage > 1 ? "&p=" + floorpage.ToString() : "";
                            paras = paras != "" ? "?" + paras.Trim('&') : "";
                            paras += "#f_" + f.ToString();
                            return Redirect(currenturl + paras);
                        }
                        NoteModel note = new NoteModel();
                        note.CateId = id;
                        note.UserName = User.Identity.Name;
                        pager.PageSize = configinfo.NotePagerCount;
                        pager = myService.GetArticlePaging(pager, 0, id);
                        ViewBag.PageNo = p ?? 1;
                        ViewBag.PageCount = pager.PageCount;
                        ViewBag.CateId = id;
                        ViewData["NoteList"] = pager.Entity;
                        return View(WebUtils.GetViewName(category.CustomView, "Note"), note);
                    //文章列表
                    default:
                        int iscommend = commend ?? 0;
                        ViewBag.Commend = iscommend;
                        pager.PageSize = configinfo.CatePagerCount;
                        bool HasSub = true;//是否还有子分类
                        if (Utils.StrToInt(category.SubCount) > 0)
                        {
                            ViewData["CateLinks"] = myService.GetSonCategoryList(Utils.StrToInt(category.CateId));
                            pager = myService.GetArticlePaging(pager, 0, myService.GetCategoryIds(id), iscommend);
                        }
                        else
                        {
                            if (category.ParentId != "0")
                                ViewData["CateLinks"] = myService.GetSonCategoryList(Utils.StrToInt(category.ParentId));
                            else
                                ViewData["CateLinks"] = new List<CategoryModel>();
                            pager = myService.GetArticlePaging(pager, 0, id, iscommend);
                            HasSub = false;
                        }
                        ViewBag.HasSub = HasSub;
                        ViewBag.PageNo = p ?? 1;
                        ViewBag.PageCount = pager.PageCount;
                        ViewBag.CateId = id;
                        string jsonSummaryImg = "";
                        pager.Entity = GetNewArticleQuery(pager.Entity as IQueryable<blog_varticle>, out jsonSummaryImg);
                        ViewBag.SummaryImgs = jsonSummaryImg;
                        return View(WebUtils.GetViewName(category.CustomView, "Category"),pager.Entity);
                }
            }
            catch
            { return View("Error"); }
        }

        /// <summary>
        /// 留言本NoteBook
        /// </summary>
        public ActionResult NoteBook(int? p)
        {
            CategoryModel category = myService.GetCategoryByReName("NoteBook");
            ViewBag.Title = category.CateName;
            ViewBag.WebPath = myService.GetCategoryPathUrl(category.Path);
            Pager pager = new Pager();
            pager.PageNo = p ?? 1;

            NoteModel note = new NoteModel();
            note.CateId = Utils.StrToInt(category.CateId);
            note.UserName = User.Identity.Name;
            pager.PageSize = configinfo.NotePagerCount;
            pager = myService.GetArticlePaging(pager, 0, note.CateId);
            ViewBag.PageNo = p ?? 1;
            ViewBag.PageCount = pager.PageCount;
            ViewBag.CateId = note.CateId;
            ViewData["NoteList"] = pager.Entity;
            return View(WebUtils.GetViewName(category.CustomView, "Note"), note);
        }

        /// <summary>
        /// 标签文章列表
        /// </summary>
        public ActionResult Tag(string key, int? p)
        {
            Pager pager = new Pager();
            pager.PageNo = p ?? 1;
            pager.PageSize = configinfo.CatePagerCount;
            pager = myService.GetTagArticlePaging(pager, 1, key.Replace("@", "."));
            ViewBag.PageNo = p ?? 1;
            ViewBag.PageCount = pager.PageCount;
            ViewBag.Path = "["+res.Tag+"] "+key.Replace("@", ".");
            string jsonSummaryImg = "";
            pager.Entity = GetNewArticleQuery(pager.Entity as IQueryable<blog_varticle>, out jsonSummaryImg);
            ViewBag.SummaryImgs = jsonSummaryImg;
            return View(pager.Entity);
        }

        /// <summary>
        /// 文章归档
        /// </summary>
        public ActionResult Archives(int year, int month, int? p)
        {
            Pager pager = new Pager();
            pager.PageNo = p ?? 1;
            pager.PageSize = configinfo.CatePagerCount;
            pager = myService.GetArchivesArticlePaging(pager,1,year,month);
            ViewBag.PageNo = p ?? 1;
            ViewBag.PageCount = pager.PageCount;
            ViewBag.Path = "["+res.Archive+"] " + year.ToString()+"/"+month.ToString();
            string jsonSummaryImg = "";
            pager.Entity = GetNewArticleQuery(pager.Entity as IQueryable<blog_varticle>, out jsonSummaryImg);
            ViewBag.SummaryImgs = jsonSummaryImg;
            return View("Tag", pager.Entity);
        }

        /// <summary>
        /// 文章按天归档
        /// </summary>
        public ActionResult ArchivesDate(int year, int month, int day, int? p)
        {
            Pager pager = new Pager();
            pager.PageNo = p ?? 1;
            pager.PageSize = configinfo.CatePagerCount;
            pager = myService.GetArchivesArticlePaging(pager, 1, year, month,day);
            ViewBag.PageNo = p ?? 1;
            ViewBag.PageCount = pager.PageCount;
            ViewBag.Path = year.ToString() + "/" + month.ToString() + "/" + day.ToString();
            string jsonSummaryImg = "";
            pager.Entity = GetNewArticleQuery(pager.Entity as IQueryable<blog_varticle>, out jsonSummaryImg);
            ViewBag.SummaryImgs = jsonSummaryImg;
            return View("Tag", pager.Entity);
        }
        

        /// <summary>
        /// 文章页
        /// </summary>
        public ActionResult Article(int id)
        {
            try
            {
                blog_varticle varticle = new blog_varticle();
                varticle = myService.GetVArticleByID(id);
                ViewBag.Title = WebUtils.MyString(varticle.seotitle,varticle.title);
                string metaDescription = string.IsNullOrWhiteSpace(varticle.seodescription) ? "" : "<meta content=\"" + varticle.seodescription + "\" name=\"Description\" />\r\n";
                string metaKeywords = string.IsNullOrWhiteSpace(varticle.seokeywords) ? "" : "<meta content=\"" + varticle.seokeywords + "\" name=\"keywords\" />\r\n";
                string metaInfo = WebUtils.MyString(varticle.seometas) + "\r\n";
                ViewBag.Seo = metaDescription + metaKeywords + metaInfo;
                ViewBag.ArticleId = varticle.id;
                ViewBag.WebPath = myService.GetCategoryPathUrl(varticle.catepath);
                return View("Article", varticle);
            }
            catch
            { return View("Error"); }
        }

        /// <summary>
        /// 文章页
        /// </summary>
        public ActionResult ArticleByKey(string key)
        {
            try
            {
                int articleid = Utils.StrToInt(key);
                if (articleid > 0)
                    return Article(articleid);
                blog_varticle varticle = new blog_varticle();
                varticle = myService.GetArticleByReName(key);
                if (varticle != null)
                {
                    return Article(varticle.id);
                }
                else
                { 
                    return View("Error"); 
                }
            }
            catch
            { return View("Error"); }
        }

        /// <summary>
        ///  异步获取文章相关信息
        /// </summary>
        [HttpPost]
        public ActionResult AjaxArticleInfo(int id)
        {
            Hashtable hash = new Hashtable();
            try
            {
                blog_varticle varticle = new blog_varticle();
                varticle = myService.GetVArticleByID(id);
                varticle.viewcount++;
                myService.UpdateArticle(varticle);
                hash["error"] = 0;
                hash["viewcount"] = varticle.viewcount;
                hash["digg_favor"] = varticle.favor;
                hash["digg_against"] = varticle.against;
                hash["digg_isvote"] = IsVote(id);
                hash["digg_tip"] = IsVote(id) ? res.Vote_Tip1 : res.Vote_Tip2;
                hash["commentcount"] = varticle.subcount;
                hash["prenextlink"] = GetNextPreArticleLink(id);
                hash["isLogIn"] = Request.IsAuthenticated;
                hash["isValidationCode"] = configinfo.IfValidateCode==1;
                hash["mustLogIn"] = configinfo.UserPermission == 1;
                hash["typeid"] = varticle.typeid;
                if (Request.IsAuthenticated)
                {
                    hash["user"] = User.Identity.Name;
                }
                else
                {
                    hash["user"] = "";
                }
                return Json(hash, "text/html;charset=UTF-8");
            }
            catch
            {
                hash["error"] = 1;
                return Json(hash, "text/html;charset=UTF-8");
            }
        }

        /// <summary>
        ///  导航
        /// </summary>
        public ActionResult GetNav()
        {
            var navs = myService.GetCategories();
            return Content("navstr", "text/html;charset=UTF-8");
        }

        /// <summary>
        ///  文章评论
        /// </summary>
        public ActionResult Reply(int id)
        {
            ViewBag.CI = configinfo;
            ReplyModel reply = new ReplyModel();
            blog_varticle article = myService.GetVArticleByID(id);
            CategoryModel category = myService.GetCategoryByID(article.cateid);
            reply.ArticleId = id;
            reply.CateId = article.cateid;
            if (category.ReplyPermit == "1" && article.replypermit==1)
                reply.ReplyPermit = 1;
            else
                reply.ReplyPermit = 2;
            return PartialView("_Comment", reply);
        }

        /// <summary>
        ///  提交/修改评论
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AjaxReply(ReplyModel model)
        {
            try
            {
                if (configinfo.UserPermission == 1 && !Request.IsAuthenticated)
                    return Content("0", "text/html;charset=UTF-8");

                if (ModelState.IsValid)
                {
                    if (configinfo.IfValidateCode == 1)
                    {
                        if (model.ValidationCode != HttpContext.Session["validationCode"].ToString())
                            return Content("-1", "text/html;charset=UTF-8");
                    }
                    if (model.ReplyId > 0 && User.Identity.Name == model.UserName.Trim())
                    {
                        blog_article article = myService.GetArticleByID(model.ReplyId);
                        article.title = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Email) ? "" : model.Email);
                        article.summary = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Url) ? "" : model.Url);
                        article.content = WebUtils.FileterData(model.Content, model.DataType);
                        myService.UpdateArticle(article);
                        return Content(article.orderid.ToString(), "text/html;charset=UTF-8");
                    }
                    blog_varticle obj = InitialArticleModel.VArticle();
                    CategoryModel category = myService.GetCategoryByID(model.CateId);
                    obj.title = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Email) ? "" : model.Email);
                    obj.summary = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Url) ? "" : model.Url);
                    obj.content = WebUtils.FileterData(model.Content, model.DataType);
                    obj.typeid = Utils.StrToInt(category.Type);
                    obj.cateid = model.CateId;
                    obj.catepath = category.Path;
                    obj.articleid = model.ArticleId;
                    obj.ip = Utils.GetIP();
                    obj.layer = 1;
                    obj.parentid = model.ArticleId;
                    if (Request.IsAuthenticated)
                    {
                        obj.userid = 1;
                        obj.username = User.Identity.Name;
                    }
                    else
                    {
                        obj.userid = 0;
                        obj.username = model.UserName;
                    }
                    int re = myService.AddArticle(obj);
                    string emailtitle = "[" + configinfo.Webtitle + " " + res.CommentReplyEmail + "]";
                    new sendDelegate(SendEmails).BeginInvoke(model.Content, emailtitle, "", re, model.ArticleId, obj.userid, obj.username, null, null);
                    return Content(myService.GetArticleByID(re).orderid.ToString(), "text/html;charset=UTF-8");
                }
                return Content("0", "text/html;charset=UTF-8");
            }
            catch
            {
                return Content("0", "text/html;charset=UTF-8");
            }
        }

        /// <summary>
        ///  根据楼层获取该页评论(异步)
        /// </summary>
        public ActionResult CommentListByFloor(int id, int f)
        {
            int pageno = myService.GetCommentPageNo(configinfo.CommentPagerCount, id, f);
            return CommentList(id, pageno);
        }

        /// <summary>
        ///  评论列表(异步)
        /// </summary>
        public ActionResult CommentList(int id, int? p)
        {
            int page = (p ?? 1) > 0 ? (p ?? 1) : 1;
            Pager pager = new Pager();
            pager.PageNo = page;
            pager.PageSize = configinfo.CommentPagerCount;
            pager = myService.GetReplyPaging(pager, id);
            ViewBag.PageNo = page;
            ViewBag.PageCount = pager.PageCount;
            ViewBag.ArticleId = id;
            AjaxPager ajaxpager = new AjaxPager(3, page, pager.PageCount);
            ViewBag.AjaxPager = ajaxpager.getPageInfoHtml();
            return PartialView("_CommentList", pager.Entity);
        }

        //异步判断验证码填写是否正确
        [HttpPost]
        public ActionResult ValidationCodeJudge(string code)
        {
            if (configinfo.IfValidateCode == 1 && code != HttpContext.Session["validationCode"].ToString())
                return Content("0", "text/html;charset=UTF-8");
            else
                return Content("1", "text/html;charset=UTF-8");
        }

        /// <summary>
        ///  提交/修改留言
        /// </summary>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Note(NoteModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    CategoryModel category = myService.GetCategoryByID(model.CateId);
                    if (configinfo.UserPermission == 1 && !Request.IsAuthenticated)
                        return Redirect(WebUtils.GetCateUrl(category));

                    if (configinfo.IfValidateCode == 1)
                    {
                        if (model.ValidationCode != HttpContext.Session["validationCode"].ToString())
                            return Redirect(WebUtils.GetCateUrl(category));
                    }

                    blog_varticle obj = InitialArticleModel.VArticle();

                    if (model.ReplyId > 0 && User.Identity.Name == model.UserName.Trim())
                    {
                        obj = myService.GetVArticleByID(model.ReplyId);
                        obj.title = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Email) ? "" : model.Email);
                        obj.summary = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Url) ? "" : model.Url);
                        obj.content = WebUtils.FileterData(model.Content, model.DataType);
                        myService.UpdateArticle(obj);
                        return Redirect(WebUtils.GetCateUrl(category) + "?f=" + obj.orderid.ToString());
                    }
                    obj.typeid = Utils.StrToInt(category.Type);
                    obj.cateid = model.CateId;
                    obj.catepath = category.Path;
                    obj.title = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Email) ? "" : model.Email);
                    obj.summary = Utils.RemoveHtml(string.IsNullOrWhiteSpace(model.Url) ? "" : model.Url);
                    obj.content = WebUtils.FileterData(model.Content, model.DataType);
                    if (Request.IsAuthenticated)
                    {
                        obj.userid = 1;
                        obj.username = User.Identity.Name;
                    }
                    else
                    {
                        obj.userid = 0;
                        obj.username = model.UserName;
                    }
                    int re = myService.AddArticle(obj);
                    string emailtitle = configinfo.Webtitle + " " + res.NoteReplyEmail;
                    string authorinfo = obj.username;
                    if (obj.userid == 1)
                    {
                        authorinfo = "<a href=\"" + configinfo.Weburl + "/u/" + HttpUtility.UrlEncode(obj.username, System.Text.Encoding.UTF8) + "\" target=\"_blank\">" + obj.username + "</a>";
                    }
                    string emailcontent = model.Content + "<br><br>By " + authorinfo + "<br><hr>Url:" + configinfo.Weburl + WebUtils.GetCateUrl(category) + "?f=" + myService.GetArticleByID(re).orderid.ToString();
                    new sendDelegate(SendEmails).BeginInvoke(model.Content, emailtitle, emailcontent, re, 0, obj.userid, obj.username, null, null);
                    return Redirect(WebUtils.GetCateUrl(category));
                }
                return View("Error");
            }
            catch
            { return View("Error"); }
        }

        /// <summary>
        ///  提交评分
        /// </summary>
        [HttpPost]
        public ActionResult AjaxVote(int articleid,int vote)
        {
            try
            {
                if (IsVote(articleid))
                    return VoteJsonRe(1, res.Vote_Tip1, 0);
                if (Request.Cookies["article.vote"] == null)
                {
                    HttpCookie voteCookie = new HttpCookie("article.vote");
                    voteCookie["articleid"] = articleid.ToString()+",";
                    voteCookie.Expires = DateTime.Now.AddDays(7d);
                    Response.Cookies.Add(voteCookie);
                }
                else
                {
                    string cookieString = Request.Cookies["article.vote"]["articleid"];
                    string[] cookies = cookieString.Split(new char[] { ',' });
                    if (!cookies.Contains(articleid.ToString()))
                    {
                        HttpCookie voteCookie = new HttpCookie("article.vote");
                        voteCookie["articleid"] = cookieString + articleid.ToString() + ",";
                        voteCookie.Expires = DateTime.Now.AddDays(7d);
                        Response.Cookies.Add(voteCookie);
                    }
                }
                int re = 0;
                blog_varticle varticle = new blog_varticle();
                varticle = myService.GetVArticleByID(articleid);
                if (vote == 1)
                {
                    varticle.favor++;
                    re = varticle.favor;
                }
                else
                {
                    varticle.against++;
                    re = varticle.against;
                }
                myService.UpdateArticle(varticle);
                return VoteJsonRe(0, res.Vote_Tip3, re);
            }
            catch
            {
                return VoteJsonRe(1, res.Ajax_Error, 0);  
            }
        }

        /// <summary>
        /// 投票返回Json提示
        /// </summary>
        private JsonResult VoteJsonRe(int error, string message, int value)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = error;
            hash["message"] = message;
            hash["value"] = value.ToString();
            return Json(hash, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 是否已投过票
        /// </summary>
        private bool IsVote(int articleid)
        {
            if (Request.Cookies["article.vote"] == null)
                return false;

            string cookieString = Request.Cookies["article.vote"]["articleid"];
            if (string.IsNullOrWhiteSpace(cookieString))
                return false;
            else
            {
                string[] cookies = cookieString.Split(new char[] { ',' });
                if (cookies.Contains(articleid.ToString()))
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 上一篇，下一篇文章链接
        /// </summary>
        private string GetNextPreArticleLink(int id)
        {
            string linkstr = "";
            blog_varticle prearticle = myService.GetPreviewArticle(id);
            blog_varticle nextarticle = myService.GetNextArticle(id);

            if (prearticle != null && !string.IsNullOrWhiteSpace(prearticle.title))
                linkstr += "<p>" + res.Previous + "：<a href=\"" + WebUtils.GetYQUrl(prearticle) + "\">" + prearticle.title + "</a></p>";
            if (nextarticle != null && !string.IsNullOrWhiteSpace(nextarticle.title))
                linkstr += "<p>" + res.Next + "：<a href=\"" + WebUtils.GetYQUrl(nextarticle) + "\">" + nextarticle.title + "</a></p>";
            return linkstr;
        }

        /// <summary>
        /// 上一个，下一个相册链接
        /// </summary>
        private string GetNextPreAlbumLink(int id)
        {
            string linkstr = "";
            blog_varticle prearticle = myService.GetPreviewArticle(id,4);
            blog_varticle nextarticle = myService.GetNextArticle(id,4);

            if (prearticle != null && !string.IsNullOrWhiteSpace(prearticle.title))
                linkstr += "<p>" + res.PreviousAlbum + "：<a href=\"" + WebUtils.GetYQUrl(prearticle) + "\">" + prearticle.title + "</a></p>";
            if (nextarticle != null && !string.IsNullOrWhiteSpace(nextarticle.title))
                linkstr += "<p>" + res.NextAlbum + "：<a href=\"" + WebUtils.GetYQUrl(nextarticle) + "\">" + nextarticle.title + "</a></p>";
            return linkstr;
        }


        /// <summary>
        /// 相册页
        /// </summary>
        public ActionResult AlbumByKey(string key)
        {
            try
            {
                int id = Utils.StrToInt(key);
                if (id > 0)
                    return Album(id);
                blog_varticle varticle = myService.GetArticleByReName(key);
                if (varticle != null)
                {
                    return Album(varticle.id);
                }
                else
                {
                    return View("Error");
                }
            }
            catch
            { return View("Error"); }
        }

        /// <summary>
        /// 相册展示页
        /// </summary>
        public ActionResult Album(int id)
        {
            try
            {
                //最新4个相册
                ViewBag.NewAlbums = myService.GetAlbums(0, 4);
                blog_varticle varticle = myService.GetVArticleByID(id);
                AlbumModel album = myService.GetAlbum(varticle);
                ViewBag.Title = varticle.title;
                ViewBag.ArticleId = varticle.id;
                album.AlbumPath = myService.GetCategoryPathUrl(varticle.catepath);
                ViewBag.VoteTip = IsVote(id) ? res.Vote_Tip1 : res.Vote_Tip2;
                ViewBag.PreNextLink = GetNextPreAlbumLink(varticle.id);
                return View("Album",album);
            }
            catch
            { return View("Error"); }
        }

        /// <summary>
        /// 站点rss
        /// </summary>
        public RssResult Rss()
        {
            return new RssResult(configinfo.Webtitle, configinfo.WebDescription, configinfo.Weburl + "/rss", myService.GetRss(myService.GetArticles(1, 0, 20).ToList()));
        }

        /// <summary>
        /// 评论rss
        /// </summary>
        public RssResult CommentRss()
        {
            return new RssResult(configinfo.Webtitle+" - "+res.LatestComments, configinfo.WebDescription, configinfo.Weburl + "/commentrss", myService.GetCommentRss(myService.GetReplyArticles(1, 0, 20).ToList()));
        }

        /// <summary>
        /// 关键字搜索
        /// </summary>
        public ActionResult Search(string key, int? p)
        {
            Pager pager = new Pager();
            pager.PageNo = p ?? 1;
            pager.PageSize = configinfo.CatePagerCount;
            pager = myService.GetKeySearchPaging(pager, 1, key);
            ViewBag.PageNo = p ?? 1;
            ViewBag.PageCount = pager.PageCount;
            ViewBag.Path = "[" + res.SearchKey + "] " + key;
            string jsonSummaryImg = "";
            pager.Entity = GetNewArticleQuery(pager.Entity as IQueryable<blog_varticle>, out jsonSummaryImg);
            ViewBag.SummaryImgs = jsonSummaryImg;
            return View("Tag", pager.Entity);
        }

        /// <summary>
        ///  文章列表(异步)
        /// </summary>
        public ActionResult JsonArticleList(int cid, int? p)
        {
            Pager pager = new Pager();
            pager.PageNo = p ?? 1;

            if (cid > 0)
            {
                CategoryModel category = myService.GetCategoryByID(cid);
                pager.PageSize = configinfo.CatePagerCount;
                if (Utils.StrToInt(category.SubCount) > 0)
                {
                    pager = myService.GetArticlePaging(pager, 0, myService.GetCategoryIds(cid));
                }
                else
                {
                    pager = myService.GetArticlePaging(pager, 0, cid);
                }
            }
            else
            {
                pager.PageSize = configinfo.IndexPagerCount;
                pager = myService.GetArticlePaging(pager, 1, 0);
            }
            string jsonSummaryImg = "";
            pager.Entity = GetNewArticleQuery(pager.Entity as IQueryable<blog_varticle>, out jsonSummaryImg);

            Hashtable hash = new Hashtable();
            hash["pageinfo"] = pager.PageCount > (p ?? 1) ? (p ?? 1) + 1 : 0;
            hash["articles"] = pager.Entity;
            return Json(hash, "text/html;charset=UTF-8");
        }

        /// <summary>
        /// 评论/回复删除
        /// </summary>
        [HttpPost]
        [Authorize]
        public ActionResult UserArticleDel(int id)
        {
            try
            {
                blog_article article = myService.GetArticleByID(id);
                if(User.IsInRole("Admin") || (User.Identity.Name == article.username.Trim() && article.userid == 1))
                {
                    myService.DelArticle(article);
                }
            }
            catch (Exception)
            {
                return Content("1", "text/html;charset=UTF-8");
            }
            return Content("0", "text/html;charset=UTF-8");
        }

        /// <summary>
        /// email异步发送委托
        /// </summary>
        /// <param name="txt"></param>
        delegate void sendDelegate(string txt, string title, string content, int id, int parentid,int authorid, string author);

        /// <summary>
        /// 发送email
        /// </summary>
        private void SendEmails(string txt, string title, string content, int id, int parentid, int authorid, string author)
        {
            try
            {
                if (configinfo.IfSendReplyEmail == 2)
                    return;
                string etitle = title;
                string econtent = content;
                List<string> lst = WebUtils.GetUsersFromTxt(txt);

                if (lst.Count > 0 && parentid > 0)
                {
                    string authorinfo = author;
                    if (authorid == 1)
                    {
                        authorinfo = "<a href=\"" + configinfo.Weburl + "/u/" + HttpUtility.UrlEncode(author, System.Text.Encoding.UTF8) + "\" target=\"_blank\">" + author + "</a>";
                    }
                    blog_varticle varticle = new blog_varticle();
                    varticle = myService.GetVArticleByID(parentid);
                    etitle = etitle + " Re:" + varticle.title;
                    econtent = "#Re:" + varticle.title + "<br><br>" + txt + "<br><hr>By " + authorinfo + "<br>URL:" + configinfo.Weburl + varticle.url + "#" + id.ToString();
                }

                foreach (string user in lst)
                {
                    string email = GetUserEmail(user);
                    if (email != "")
                    {
                        WebUtils.SendSysMail(email, etitle, econtent.Replace("\r\n", "<br>"));
                    }
                }
            }
            catch
            { }
        }

        /// <summary>
        /// 获取用户email
        /// </summary>
        private string GetUserEmail(string user)
        {
            try
            {
                ProfileBase objProfile = System.Web.Profile.ProfileBase.Create(user);
                if (objProfile.GetPropertyValue("isSendEmail").ToString() == "2")
                    return "";
                string email = (String)objProfile.GetPropertyValue("email");
                if (string.IsNullOrEmpty(email))
                {
                    MembershipUser currentUser = Membership.GetUser(user, false);
                    email = currentUser.Email;
                }
                return email;
            }
            catch
            {
                return "";
            }
        }

    }
}
